package com.ddtj.demo1.component.exception;

import com.ddtj.demo1.pojo.AjaxResult;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult validatedException(MethodArgumentNotValidException validException){
        String defaultMessage = validException.getBindingResult().getFieldError().getDefaultMessage();
        return AjaxResult.conflict(defaultMessage);
    }

    @ExceptionHandler(BindException.class)
    public AjaxResult validatedBindindExceptionHandler(BindException bindException){
        String defaultMessage = bindException.getAllErrors().get(0).getDefaultMessage();
        return AjaxResult.error(defaultMessage);
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        return AjaxResult.error(e.getMessage());
    }
}
